﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using YunCMS.Common;
using YunCMS.BLL;
using YunCMS.Model;

namespace YunCMS.Web.Admin
{
    public partial class Login1 : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //TODO:
                txtAccount.AutoCompleteType = AutoCompleteType.None;
            }
        }

        private void GetUser(string username, YCUserBLL bll)
        {
            if (Session[Const.USER_INFO] != null)
            {
                Session.Remove(Const.USER_INFO);
            }
            YCUser user = bll.GetYCUser(username);
            if (user != null)
            {
                Session[Const.USER_INFO] = user;
            }
            if (user.Role.HasValue)
            {
                GetAuthority(user.Role.Value);
            }
        }

        private void GetAuthority(int roleID)
        {
            if (Session[Const.USER_AUTHORITY] != null)
            {
                Session.Remove(Const.USER_AUTHORITY);
            }
            YCUserRoleBLL bll = new YCUserRoleBLL();
            YCUserRole role = bll.GetYCUserRoleWithActions(roleID);
            if (role != null)
            {
                Session[Const.USER_AUTHORITY] = role;
            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            if (Session["verifycode"] != null &&
                string.Compare(Session["verifycode"].ToString(), txtVerifyCode.Text.Trim(), true) == 0)
            {
                try
                {
                    YCUserBLL userBll = new YCUserBLL();
                    string uname = txtAccount.Text.Trim(),
                        pwd = txtPwd.Text.Trim();

                    if (userBll.IsExist(uname, pwd))
                    {
                        Session["username"] = uname;
                        Session["password"] = pwd;
                        GetUser(uname, userBll);
                        Response.Redirect("index.aspx");
                    }
                    else
                    {
                        JScript.Alert("密码或用户名错误！", this);
                    }
                }
                catch (Exception error)
                {
                    Response.Write(error.ToString());
                }
            }
            else
            {
                JScript.Alert("验证码错误！", this);
            }
        }
    }
}